from csgencoder import *
from csgdecoder import *
class FrameHandler:
    def __init__(self):
        # 初始化FrameHandler，设置默认的响应帧构建函数
        self.action_map = {
            ('02', 'E0001000'): self.handle_di_e0001000,
            ('02', 'E0001001'): self.handle_di_e0001001,
            # 添加更多的AFN和DI处理映射
        }

    def parse_frame(self, raw_frame):
        # 解析帧的函数
        return parse_frame(raw_frame)

    def handle_frame(self, frame_info):
        # 根据frame_info处理帧并构建响应
        afn = frame_info['User Data Info']['AFN']
        di = frame_info['User Data Info']["DI"]
        print(afn, di)
        action = self.action_map.get((afn, di))

        if action:
            rsp_frame = action(frame_info)
            return rsp_frame
        else:
            # 没有对应的处理函数，返回None或者默认响应
            return None

    def handle_di_e0001000(self, frame_info):
        # 处理DI为E0001000的逻辑
        # 构建对应的响应帧
        rsp_frame = build_confirmation_frame(frame_info['User Data Info']['SEQ'])  # 假设有一个函数来构建确认帧
        return rsp_frame

    def handle_di_e0001001(self, frame_info):
        # 处理DI为E0001001的逻辑
        # 构建对应的响应帧或执行其他操作
        return build_confirmation_frame(frame_info['User Data Info']['SEQ']) 

    # 添加更多的处理函数来处理不同的DI

def handle_client(client_socket, client_address):
    try:
        frame_handler = FrameHandler()
        while True:
            # 接收数据
            raw_frame = client_socket.recv(1024)
            if not raw_frame:
                break

            print("rx {}:".format(client_address), raw_frame.hex())

            # 解析帧
            frame_info = frame_handler.parse_frame(raw_frame)
            if frame_info:
                print("frame_info:", frame_info)

                # 处理帧并构建响应
                rsp_frame = frame_handler.handle_frame(frame_info)
                if rsp_frame:
                    client_socket.sendto(rsp_frame, client_address)
                    print("tx:", rsp_frame.hex())
            else:
                print("Error parsing frame from {}: {}".format(client_address, frame_info))

    except Exception as e:
        print("Error handling client {}: {}".format(client_address, e))
    finally:
        client_socket.close()

# 你可以继续扩展FrameHandler类来处理更多的AFN和DI组合。